<script setup lang="ts">
import { reactive, ref, watch, onMounted } from "vue"
import { fetchSelectList, fetchEnumSelectList } from "@/api/common"
import { saveUserDataApi, deleteUserDataApi, getUserDataApi, updateEnablApi } from "@/api/user"
import { type UserData } from "@/api/user/types/user"
import { type SelectData } from "@/api/common/types/common"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { cloneDeep } from "lodash-es"
import { mount } from "@vue/test-utils"
import { getRandomType } from "@/utils/common"
import { checkPermission } from "@/utils/permission"

defineOptions({
  // 命名当前组件
  name: "User"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const DEFAULT_FORM_DATA = {
  id: 0,
  userCode: "",
  userName: "",
  assignee: "",
  type: "",
  devManager: false,
  groupId: 0,
  enable: false
}
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<UserData>(cloneDeep(DEFAULT_FORM_DATA))

const formRules = reactive<FormRules>({
  assignee: [{ required: true, trigger: "blur", message: "请输入jira账号" }]
  // note: [{ required: true, trigger: "blur", message: "请输入备注" }]
})
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true

    saveUserDataApi(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
//#endregion

//更新用户状态
const updateEnable = (row: UserData) => {
  const id = row.id
  if (!id) return
  const enbale = row.enable
  const text = enbale ? "禁用" : "启用"
  ElMessageBox.confirm(`确认${text}用户吗`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    updateEnablApi(id, !enbale).then(() => {
      ElMessage.success("修改成功")
      getTableData()
    })
  })
}

//#region 删
const _handleDelete = (row: UserData) => {
  const id = row.id
  if (!id) return

  ElMessageBox.confirm(`正在删除用户：${row.userName}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteUserDataApi(id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const handleUpdate = (row: UserData) => {
  dialogVisible.value = true
  formData.value = cloneDeep(row)
}
//#endregion

// 小组下拉框
const groupSelectOptions = ref<SelectData[]>([])
const fetchGroupSelectOptions = async () => {
  const data = await fetchSelectList("group")
  groupSelectOptions.value = data.data
}
//用户类型下拉框
const userTypeOptions = ref<SelectData[]>([])

const fetchUserTypeOptions = async () => {
  const data = await fetchEnumSelectList("UserType")
  userTypeOptions.value = data.data
}

//#region 查
const tableData = ref<UserData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  userCode: "",
  userName: "",
  type: "",
  devManager: undefined,
  groupId: undefined,
  enable: undefined
})

const getTableData = () => {
  loading.value = true
  getUserDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    userCode: searchData.userCode,
    userName: searchData.userName,
    type: searchData.type,
    devManager: searchData.devManager ? searchData.devManager : null,
    groupId: searchData.groupId ? searchData.groupId : null,
    enable: searchData.enable
  })
    .then(({ data }) => {
      paginationData.total = data.total
      tableData.value = data.datas
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()

  handleSearch()
}
onMounted(() => {
  fetchGroupSelectOptions()
  fetchUserTypeOptions()
})
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })

mount
</script>
<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="groupId" label="小组">
          <el-select
            v-model="searchData.groupId"
            clearable
            placeholder="请选择小组"
            style="width: 200px"
            :empty-values="[null]"
          >
            <el-option v-for="item in groupSelectOptions" :key="item.id" :label="item.text" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item prop="type" label="用户类型">
          <el-select
            v-model="searchData.type"
            clearable
            placeholder="请选择类型"
            style="width: 180px"
            :empty-values="[null]"
          >
            <el-option v-for="item in userTypeOptions" :key="item.id" :label="item.text" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item prop="devManager" label="是否项目经理">
          <el-select
            v-model="searchData.devManager"
            clearable
            placeholder="是否项目经理"
            style="width: 200px"
            :empty-values="[null]"
          >
            <el-option label="是" :value="true" />
            <el-option label="否" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item prop="enable" label="用户状态">
          <el-select
            v-model="searchData.enable"
            clearable
            placeholder="用户状态"
            style="width: 180px"
            :empty-values="[null]"
          >
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>

        <el-form-item prop="userName" label="用户名">
          <el-input v-model="searchData.userName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="userCode" label="工号">
          <el-input v-model="searchData.userCode" placeholder="请输入" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <!-- <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">新增用户</el-button>
          <el-button type="danger" :icon="Delete">批量删除</el-button> -->
        </div>
        <div>
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
          <!-- <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip> -->
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="userCode" label="工号" align="center" />
          <el-table-column prop="userName" label="用户名" align="center" />
          <el-table-column prop="assignee" label="jira用户" align="center" />
          <el-table-column prop="groupName" label="小组" align="center">
            <template #default="scope">
              <el-tag :type="getRandomType(scope.row.groupId)" effect="dark" round> {{ scope.row.groupName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="typeText" label="类型" align="center" />
          <el-table-column prop="enable" label="状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.enable" type="success" effect="plain" disable-transitions>启用</el-tag>
              <el-tag v-else type="danger" effect="plain" disable-transitions>禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="devManager" label="是否开发经理" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.devManager" type="primary" effect="plain" disable-transitions>是</el-tag>
              <el-tag v-else type="info" effect="plain" disable-transitions>否</el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="240" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button
                :type="scope.row.enable ? 'warning' : 'success'"
                size="small"
                v-if="checkPermission(['admin'])"
                @click="updateEnable(scope.row)"
                >{{ scope.row.enable ? "禁用" : "启用" }}</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id === 0 ? '新增用户' : '修改用户'"
      @closed="resetForm"
      width="40%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="" label="用户">
          <el-text class="mx-1">{{ formData.userName }}</el-text>
          <el-text class="mx-1" type="primary" size="small"> ({{ formData.userCode }}) </el-text>
        </el-form-item>
        <el-form-item prop="groupId" label="小组">
          <el-select v-model="formData.groupId" clearable placeholder="请选择小组">
            <el-option v-for="item in groupSelectOptions" :key="item.id" :label="item.text" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item prop="assignee" label="jira账号">
          <el-input v-model="formData.assignee" placeholder="请输入" />
        </el-form-item>

        <el-form-item prop="devManager" label="是否开发经理">
          <el-select v-model="formData.devManager" placeholder="是否项目经理">
            <el-option label="否" :value="false" />
            <el-option label="是" :value="true" />
          </el-select>
        </el-form-item>

        <el-form-item prop="type" label="类型">
          <el-select v-model="formData.type" placeholder="请选择类型" style="width: 180px" :empty-values="[null]">
            <el-option v-for="item in userTypeOptions" :key="item.id" :label="item.text" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item prop="enable" label="状态">
          <el-select v-model="formData.enable" placeholder="状态">
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading" v-if="checkPermission(['admin'])"
          >确认</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
